package com.example.caoben_back.contoller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.caoben_back.entity.po.Image;
import com.example.caoben_back.entity.po.User;
import com.example.caoben_back.entity.vo.Result;
import com.example.caoben_back.service.IImageService;
import com.example.caoben_back.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/image")
public class ImageController {

    @Autowired
    private IImageService imageService;


    // 上传图片（通用）
    @PostMapping("/upload")
    public Result<Map<String, String>> uploadImage(@RequestParam("image") MultipartFile file,
                                                  @RequestParam Integer type,
                                                  HttpServletRequest request) {
        // 从token中解析用户信息
        User user = TokenUtil.getUserFromRequest(request);
        if (user == null) {
            return Result.fail("用户未登录");
        }
        Integer userId = user.getUserId();
        
        // 实际业务：上传文件到OSS，返回URL
        String imageUrl = "https://mock-image/" + System.currentTimeMillis() + ".png";
        
        // 保存图片关系到数据库
        Image image = new Image();
        image.setImageUrl(imageUrl);
        image.setImageType(type);
        image.setTargetId(userId);
        imageService.save(image);

        return Result.success(null);
    }

    // 获取目标对象的图片列表
    @GetMapping("/list")
    public Result<Map<String, Object>> getTargetImages(@RequestParam Integer targetId,
                                                     @RequestParam Integer type) {
        List<Image> images = imageService.list(new QueryWrapper<Image>()
                .eq("target_id", targetId)
                .eq("image_type", type));
        List<String> imageUrls = images.stream()
                .map(Image::getImageUrl)
                .collect(Collectors.toList());
        Map<String, Object> data = new HashMap<>();
        data.put("imageUrls", imageUrls);
        return Result.success(data);
    }
}